from PIL import Image
import matplotlib.pyplot as plt
import numpy as np


src = np.array(Image.open('lena_gray.jpg'))  # 原图像
template = np.array(Image.open('eye_gray.jpg'))  # 模板

print(src.shape)
t_width = template.shape[1]     # 模板宽
t_height = template.shape[0]     # 模板高
s_width = src.shape[1]  # 原图像宽
s_height = src.shape[0]  # 原图像高

dst = np.zeros([s_width - t_width, s_height - t_height])        # 构造0矩阵


for i in range(0, s_width - t_width):       # 遍历原图
    for j in range(0, s_height - t_height):
        temp = src[j:t_height + j, i:t_width + i]     # 当前位置子图
        dst[i][j] = dst[i][j] + np.sum(np.abs(temp - template))   # 子图与模板的距离

abs_min = np.min(dst)
print(abs_min)



for i in range(0, s_width - t_width-1):         # 找出匹配位置的坐标点
    for j in range(0, s_height - t_height-1):
        if dst[i][j] == abs_min:
            y = i
            x = j

print(x, y)


for i in range(0, 46):      # 画出匹配位置
    src[x+i, y] = 255
    src[x, y+i] = 255
    src[x+i, y+t_height] = 255
    src[x+t_width, y+i] = 255


def img_show(np_image):      # 结果显示
    plt.imshow(np_image, cmap='gray')
    plt.show()

img_show(src)









